package com.jframe.sys.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class PropertiesUtil {

	private  Properties props = null;
	private String path = "";
	
	public void setPath(String path) {
		this.path = path;
	}

	public String getPath() {
		return path;
	}
	
	public PropertiesUtil(String path){
		this.path = path;
		init(path);
	}
	
    public static PropertiesUtil getInstance(String path){		
		return new PropertiesUtil(path);		
	}
	
	private void init(String path){
		if(path.endsWith("")){
			path = this.path;
		}
		this.props = new Properties();
		InputStream in;
		try {
			in = new BufferedInputStream(new FileInputStream(path));
			this.props.load(in);
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 *  获取关键字段�?
	 * @param key
	 * @return
	 */
	public String getKeyValue(String key){
		
		return this.props.getProperty(key);
	}
	
	/**
	 * 设置字段�?
	 * @param key
	 * @param value
	 */
	public void setKeyValue(String key,String value){
		try {
			OutputStream fos = new FileOutputStream(this.path);
			this.props.setProperty(key, value);
			try {
				this.props.store(fos, "修改�?'" + key + "' 的�?");
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 将所有的键值转换成map
	 * @return
	 */
	public Map<String ,String> loadAll(){		
		Set set = this.props.keySet();
		Map<String ,String> map = new HashMap<String,String> ();
		for(Object obj:set){
			String key = (String) obj;
			map.put(key, this.getKeyValue(key));		
		}
		return map;
	}
	
	public static void main(String [] args){
		
		String path = "E:\\test.properties";
		PropertiesUtil properties = new PropertiesUtil(path);
		System.out.println(properties.getKeyValue("name"));		
		properties.setKeyValue("name", "l2iu11");		
		System.out.println(properties.getKeyValue("name"));
		
	}

	
	
	
	
	
}
